﻿using Blm.Utils.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using VisionCloud.Core.Model.Ms;
using VisionCloud.Domain.Common;
using VisionCloud.Domain.DtoModel.Ms;
using VisionCloud.Domain.Repository.Interface.Ms;
using VisionCloud.Utility;

namespace VisionSurface.Service.Ms
{
    /// <summary>
    /// 项目服务
    /// </summary>
    public class ProjectService
    {
        public IMsProjectRepository MsProjectRepository { get; set; }

        public IMsHouseMapRepository MsHouseMapRepository { get; set; }

        public IMsPointTypeRepository MsPointTypeRepository { get; set; }

        public IMsHouseMapDetailsRepository MsHouseMapDetailsRepository { get; set; }

        public IMsMeasureTemplateRepository MsMeasureTemplateRepository { get; set; }

        public IMsProjectStandardRepository MsProjectStandardRepository { get; set; }

        public IConfiguration cfg { get; set; }

        public ILogger<ProjectService> Logger { get; set; }

        /// <summary>
        /// 获取项目的楼栋楼层
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        /// <exception cref="OperationException"></exception>
        public async ValueTask<List<ProjectBuildingFloorDto>> GetProjectBuildingFloorsAsync(Guid projectId)
        {
            var project = await MsProjectRepository.FirstOrDefaultAsync(p => p.ProjectId == projectId && !p.IsDeleted);
            if (project == null)
                throw new OperationException("YB0064".SLocalize());

            List<ProjectBuildingFloorDto> projectBuildingFloors = new List<ProjectBuildingFloorDto>();
            var details = project.Details.ToObject<List<Detail>>();
            if (details.IsNotEmpty())
            {
                foreach (var item in details)
                {
                    var buildingDto = new ProjectBuildingFloorDto
                    {
                        Id = item.Building,
                        Name = $"{item.Building}栋",
                        Standard = item.Standard
                    };
                    for (int i = 1; i <= item.Floor.ToInt32(); i++)
                    {
                        buildingDto.SubChildrens.Add(new ProjectBuildingFloorDto
                        {
                            Id = i.ToString(),
                            Name = $"{i}层",
                            Standard = item.Standard
                        });
                    }
                    buildingDto.SubChildrens = buildingDto.SubChildrens.OrderBy(p => p.Id.ToInt32()).ToList();
                    projectBuildingFloors.Add(buildingDto);
                }
            }

            return projectBuildingFloors;
        }

        /// <summary>
        /// 获取项目的户型图列表以及楼栋楼层
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public async ValueTask<ApiResult> GetHouseMapAndFloorsAsync(Guid projectId)
        {
            var housemapList = await MsHouseMapRepository.GetHouseMapAsync(new MsHouseMapCondition { ProjectId = projectId, CurrentPage = 1, PageSize = 1000 });

            var floorList = await MsHouseMapDetailsRepository.GetHouseMapBuildingFloorsAsync(projectId);

            var result = new HousemapBuildingFloorResponseDto
            {
                HouseMapDetails = housemapList,
                HouseMapFloors = floorList
            };

            return new ApiResult { Code = 0, Result = result };
        }

        /// <summary>
        /// 获取测量项的
        /// </summary>
        /// <param name="houseMapId"></param>
        /// <returns></returns>
        /// <exception cref="OperationException"></exception>
        public async ValueTask<List<MsMeasureTemplateDto>> GetMsMeasureItemTemplatesAsync(Guid houseMapId)
        {
            var houseMap = MsHouseMapRepository.GetById(houseMapId);
            if (houseMap == null)
            {
                //户型图不存在
                throw new OperationException("YB0120".SLocalize());
            }
            return await MsMeasureTemplateRepository.GetMeasureTemplate(houseMapId);
        }

        /// <summary>
        /// 获取站点类型详情
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async ValueTask<List<MsPointTypeDto>> GetPointTypeDetailsAsync(PointTypeDetailRequestDto dto)
        {
            return await MsPointTypeRepository.GePointTypeDetail(dto.ProjectStandardId, dto.HouseMapId, dto.ProjectId);
        }

        /// <summary>
        /// 获取人工测量项
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="OperationException"></exception>
        public async ValueTask<StandardListModel> GetArtificialStageStandardAsync(StageStandardQueryDto dto)
        {
            //项目信息
            var project = await MsProjectRepository.GetByIdAsync(dto.ProjectId);
            var detailList = project.Details.ToObject<List<Detail>>();
            var detail = detailList.SingleOrDefault(w => w.Building == dto.BuildingBlock);
            if (detail == null)
                throw new OperationException("YB0167".SLocalize());

            //标准库
            var data = MsProjectStandardRepository.Where(i => i.ProjectGuid == dto.ProjectId && i.ProjectStandardId == dto.StandardId).FirstOrDefault();
            var result = data.CopyTo<StandardListModel>();
            result.Classes = data.Content.ToObject<List<StandardClass>>();

            foreach (var classEntity in result.Classes)
            {
                classEntity.Items = classEntity.Items.Where(w => string.IsNullOrEmpty(w.SupportStandard) || w.SupportStandard.Equals(detail.Standard)).Where(w => w.Type == 0).ToList();
            }
            return result;
        }

        /// <summary>
        /// 获取机器测量项
        /// </summary>
        /// <param name="condition">查询条件</param>
        /// <returns></returns>
        public async ValueTask<List<StandardListModel>> GetSystemStageStandardAsync(Guid projectId, Guid projectStandardId)
        {
            var list = await MsProjectStandardRepository.WhereAsync(x => x.ProjectGuid == projectId && x.ProjectStandardId == projectStandardId);
            return list.Select(w => new StandardListModel()
            {
                Code = w.Code,
                ProjectGuid = w.ProjectGuid,
                ProjectStandardId = w.ProjectStandardId,
                Stage = w.Stage,
                Title = w.Title,
                Classes = w.Content.ToObject<List<StandardClass>>(),
                Templates = w.Template.ToObject<List<StandardClass>>()
            }).OrderBy(x => x.Code).ToList();
        }

        /// <summary>
        /// 获取工程阶段的测量项
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async ValueTask<ApiResult> GetStageStandardsAsync(StageStandardQueryDto dto)
        {
            var response = new StandardListResponseDto
            {
                ArtificialStandard = await GetArtificialStageStandardAsync(dto),
                RobotStandard = await GetSystemStageStandardAsync(dto.ProjectId, dto.StandardId)
            };
            return new ApiResult { Code = AjaxCode.Success, Result = response };
        }

        public async Task<string> GetHouseMapUrlById(Guid houseMapId)
        {
            var houseMap = await MsHouseMapRepository.GetAll().Where(x => x.HouseMapId == houseMapId).Select(x => new { x.DataType, x.Image_Base }).FirstOrDefaultAsync();
            var houseMapUrl = houseMap.DataType switch
            {
                0 => $"{cfg["FileServer"]}/{cfg["FileUploadFileMaster"]}/{cfg["FileUploadFileSon"]}/{houseMap.Image_Base}",
                1 => $"{cfg["FileServer"]}/algorithmreport{houseMap.Image_Base.Replace("algorithm-report", "")}",
                2 => $"{cfg["FileServer"]}/algorithmreport{houseMap.Image_Base.Replace("algorithm-report", "")}",
                _ => $"{cfg["FileServer"]}/{cfg["FileUploadFileMaster"]}/{cfg["FileUploadFileSon"]}/{houseMap.Image_Base}"
            };
            return houseMapUrl;
        }
    }
}